<template>
  <!-- 热销商品占比图表组件 -->
  <div class="com-container">
    <div class="com-chart" ref="hot"></div>
    <i class="iconfont icon-arrow-right btn-right"
      :style="{fontSize:fontSize*2+'px',color:theme==='chalk'?'#fff':'#000'}"
      @click="nextCate"></i>
    <i class="iconfont icon-arrow-lift btn-left"
      :style="{fontSize:fontSize*2+'px',color:theme==='chalk'?'#fff':'#000'}"
      @click="lastCate"></i>
    <span class="cat-name"
      :style="{fontSize:fontSize/1.5+'px',color:theme==='chalk'?'#fff':'#000'}">{{cateTitle}}</span>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  data() {
    return {
      // echarts对象
      myChart: null,
      // 数据
      hotData: null,
      // 当前一级分索引
      currentIndex: 0,
      // 字体大小
      fontSize: 0
    }
  },
  computed: {
    ...mapState(['theme']),
    // 一级分类标题
    cateTitle() {
      if (this.hotData) {
        return this.hotData[this.currentIndex].name
      } else {
        return ''
      }
    }
  },
  watch: {
    theme() {
      this.myChart.dispose()
      this.initChart()
      this.updateChart()
      this.screenAdapter()
    }
  },
  mounted() {
    this.initChart()
    this.getData()
    window.addEventListener('resize', this.screenAdapter)
    this.screenAdapter()
  },
  destroyed() {
    window.removeEventListener('resize', this.screenAdapter)
  },
  methods: {
    // 初始化echarts对象
    initChart() {
      this.myChart = this.$echarts.init(this.$refs.hot, this.theme)
      const initOption = {
        title: {
          text: '▎热销商品占比',
          top: 20,
          left: 20
        },
        legend: {
          top: '15%',
          icon: 'circle'
        },
        tooltip: {
          a: 1,
          show: true,
          formatter(arg) {
            // 三级分类
            const thirdCategory = arg.data.children
            // 计算出三级分类的数值总和
            let total = 0
            let resStr = ''
            let persent = 0
            thirdCategory.forEach(item => {
              total += item.value
            })
            thirdCategory.forEach(item => {
              persent = ((item.value / total) * 100).toFixed(2)
              // 三级分类名称：三级分类占比
              resStr += `${item.name}:${persent}%<br />`
            })
            return resStr
          }
        },
        series: [
          {
            type: 'pie',
            center: ['50%', '60%'],
            label: {
              show: false
            },
            labelLine: {
              show: false
            },
            emphasis: {
              label: {
                show: true
              }
            }
          }
        ]
      }
      this.myChart.setOption(initOption)
    },
    // 获取数据
    async getData() {
      // 处理数据后赋值给hotData
      const res = (this.hotData = await this.$getApi.getHotProduct())

      this.updateChart()
    },
    // 更新图表
    updateChart() {
      const legendData = []
      const seriesData = []
      this.hotData[this.currentIndex].children.forEach(item => {
        legendData.push({
          name: item.name
        })
        seriesData.push({
          name: item.name,
          value: item.value,
          children: item.children
        })
      })
      const dataOption = {
        legend: {
          data: legendData
        },
        series: [
          {
            data: seriesData
          }
        ]
      }
      this.myChart.setOption(dataOption)
    },
    // 图表适配浏览器窗口大小变化
    screenAdapter() {
      const titleFontSize = (this.fontSize =
        (this.$refs.hot.offsetWidth / 100) * 3.6)
      const adaptOption = {
        title: {
          textStyle: {
            fontSize: titleFontSize
          }
        },
        legend: {
          itemWidth: titleFontSize / 1.5,
          itemHeight: titleFontSize / 1.5,
          itemGap: titleFontSize / 1.5,
          textStyle: {
            fontSize: titleFontSize / 1.5
          }
        },
        series: [
          {
            radius: titleFontSize * 4.2
          }
        ]
      }
      this.myChart.setOption(adaptOption)
      this.myChart.resize()
    },
    // 点击右箭头，下一个一级分类
    nextCate() {
      if (this.currentIndex === this.hotData.length - 1) return
      this.currentIndex++
      this.updateChart()
    },
    // 点击左箭头，上一个一级分类
    lastCate() {
      if (this.currentIndex === 0) return
      this.currentIndex--
      this.updateChart()
    }
  }
}
</script>

<style scoped>
.btn-right,
.btn-left {
  position: absolute;
  top: 60%;
  transform: translateY(-50%);
  color: #fff;
  cursor: pointer;
}
.btn-right {
  right: 10%;
}
.btn-left {
  left: 10%;
}
.cat-name {
  position: absolute;
  bottom: 10%;
  right: 10%;
  color: #fff;
  font-weight: 700;
}
</style>
